//
//  ViewController.swift
//  5.5.Adding a Dynamic Snap Effect to Your UI Components
//
//  Created by joker on 15/7/31.
//  Copyright (c) 2015年 joker. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

    var squareView: UIView?
    var animator: UIDynamicAnimator?
    var snapBehavior: UISnapBehavior?
    
    func createGestureRecognizer(){
        let tap = UITapGestureRecognizer(target: self, action: "handleTap:")
        view.addGestureRecognizer(tap)
    }
    
    func createSmallSquareView(){
        squareView = UIView(frame: CGRect(x: 0, y: 0, width: 80, height: 80))
        squareView!.backgroundColor = UIColor.greenColor()
        squareView!.center = view.center
        view.addSubview(squareView!)
    }
    
    func createAnimatorAndBehaviors(){
        animator = UIDynamicAnimator(referenceView: view)
        
        let collision = UICollisionBehavior(items: [squareView!])
        collision.translatesReferenceBoundsIntoBoundary = true
        
        animator!.addBehavior(collision)
        
        snapBehavior = UISnapBehavior(item: squareView!, snapToPoint: squareView!.center)
        
        snapBehavior!.damping = 0.5
        
        animator!.addBehavior(snapBehavior!)
        
    }
    
    func handleTap(tap:UITapGestureRecognizer) {
        let tapPoint = tap.locationInView(view)
        
        if let theSnap = snapBehavior {
            animator!.removeBehavior(theSnap)
        }
        
        snapBehavior = UISnapBehavior(item: squareView!, snapToPoint: tapPoint)
        snapBehavior!.damping = 0.5
        animator!.addBehavior(snapBehavior!)
    }
    override func viewDidAppear(animated: Bool) {
        self.createGestureRecognizer()
        self.createSmallSquareView()
        self.createAnimatorAndBehaviors()
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

